package com.atguigu.tingshu.album;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-08-14 14:23
 */
@Slf4j
@Component
public class AlbumReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;


    /**
     * 监听到更新声音统计消息，更新MySQL中统计数值
     *
     * @param mqVo
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateStat(TrackStatMqVo mqVo, Message message, Channel channel) {
        String key = "";
        try {
            if (mqVo != null) {
                log.info("监听到更新声音统计消息:{}", mqVo);
                //1. 处理消费者幂等性问题（一个消息被多次消费带来数据不一致问题）
                //1.1 基于MQ消息对象中唯一标识作为Redis中Key 采用set k v ex nx命令写入Redis
                key = RedisConstant.BUSINESS_PREFIX + mqVo.getBusinessNo();
                Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", 10, TimeUnit.MINUTES);
                if (flag) {
                    //2. 更新统计数值 业务处理可能抛出异常
                    trackInfoService.updateStat(mqVo);
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("[专辑服务]监听更新声音统计消息异常：{}", e);
            //3.捕获到业务处理异常后，将消息再次进行入队，RabbitMQ再次投递消息
            redisTemplate.delete(key);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
